package com.ruoyi.statistics.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.statistics.mapper.UserAnalyseMapper;
import com.ruoyi.statistics.service.IUserAnalyseService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;

/**
 * 用户数据分析Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Service
public class UserAnalyseServiceImpl implements IUserAnalyseService 
{
    @Autowired
    private UserAnalyseMapper userAnalyseMapper;

    /**
     * 获取用户核心指标数据
     */
    @Override
    public Map<String, Object> selectUserMetrics(Map<String, Object> params)
    {
        // 设置默认时间范围（覆盖所有数据）
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        // 获取核心指标统计数据
        Map<String, Object> metrics = userAnalyseMapper.selectUserMetrics(params);
        
        return metrics != null ? metrics : new HashMap<>();
    }

    /**
     * 获取用户活跃度趋势数据
     */
    @Override
    public List<Map<String, Object>> selectUserActivityTrend(Map<String, Object> params)
    {
        // 设置默认时间范围
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        List<Map<String, Object>> trendData = userAnalyseMapper.selectUserActivityTrend(params);
        return trendData != null ? trendData : new ArrayList<>();
    }

    /**
     * 获取用户地域分布数据
     */
    @Override
    public List<Map<String, Object>> selectUserRegionDistribution(Map<String, Object> params)
    {
        // 设置默认时间范围
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        List<Map<String, Object>> regionData = userAnalyseMapper.selectUserRegionDistribution(params);
        return regionData != null ? regionData : new ArrayList<>();
    }

    /**
     * 获取用户转化漏斗数据
     */
    @Override
    public Map<String, Object> selectUserConversionFunnel(Map<String, Object> params)
    {
        // 设置默认时间范围
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        Map<String, Object> funnelData = userAnalyseMapper.selectUserConversionFunnel(params);
        return funnelData != null ? funnelData : new HashMap<>();
    }

    @Override
    public Map<String, Object> selectCommentStatistics(Map<String, Object> params) {
        return userAnalyseMapper.selectCommentStatistics(params);
    }

    @Override
    public List<Map<String, Object>> selectCommentRatingDistribution(Map<String, Object> params) {
        return userAnalyseMapper.selectCommentRatingDistribution(params);
    }

    @Override
    public Map<String, Object> selectAfterServiceStatistics(Map<String, Object> params) {
        return userAnalyseMapper.selectAfterServiceStatistics(params);
    }

    @Override
    public List<Map<String, Object>> selectAfterServiceCategory(Map<String, Object> params) {
        return userAnalyseMapper.selectAfterServiceCategory(params);
    }

    @Override
    public List<Map<String, Object>> selectCommentKeywords(Map<String, Object> params) {
        return userAnalyseMapper.selectCommentKeywords(params);
    }

    /**
     * 获取用户详情列表
     */
    @Override
    public List<Map<String, Object>> selectUserDetails(Map<String, Object> params)
    {
        // 设置默认时间范围
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        // 移除分页参数，避免与MyBatis的LIMIT语句冲突
        params.remove("pageNum");
        params.remove("pageSize");
        params.remove("offset");
        params.remove("limit");
        
        // 移除空值
        params.entrySet().removeIf(entry -> entry.getValue() == null || "".equals(entry.getValue()));
        
        try {
            List<Map<String, Object>> userList = userAnalyseMapper.selectUserDetails(params);
            return userList != null ? userList : new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 获取用户详情总数
     */
    @Override
    public Integer selectUserDetailsCount(Map<String, Object> params)
    {
        // 设置默认时间范围
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        // 移除空值
        params.entrySet().removeIf(entry -> entry.getValue() == null || "".equals(entry.getValue()));
        
        try {
            Integer total = userAnalyseMapper.selectUserDetailsCount(params);
            return total != null ? total : 0;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取用户详情数据（用于导出）
     */
    @Override
    public List<Map<String, Object>> selectUserDetailsForExport(Map<String, Object> params)
    {
        // 设置默认时间范围
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            params.put("startDate", "2025-01-01");
            params.put("endDate", "2025-12-31");
        }
        
        // 移除空值
        params.entrySet().removeIf(entry -> entry.getValue() == null || "".equals(entry.getValue()));
        
        try {
            List<Map<String, Object>> exportData = userAnalyseMapper.selectUserDetailsForExport(params);
            return exportData != null ? exportData : new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    /**
     * 计算转化率
     */
    private String calculateRate(Object current, Object previous)
    {
        if (current == null || previous == null) {
            return "0%";
        }
        
        try {
            double currentValue = Double.parseDouble(current.toString());
            double previousValue = Double.parseDouble(previous.toString());
            
            if (previousValue == 0) {
                return "0%";
            }
            
            double rate = (currentValue / previousValue) * 100;
            // 确保转化率不超过100%
            rate = Math.min(rate, 100.0);
            return String.format("%.1f%%", rate);
        } catch (NumberFormatException e) {
            return "0%";
        }
    }
    
    /**
     * 安全解析long值
     */
    private long parseLong(Object value) {
        if (value == null) {
            return 0L;
        }
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return 0L;
        }
    }
}